/**
 * By Alpha
 * Author: alixez <alixe.z@foxmail.com>
 * Date: 2017/11/2
 */
/* global window */
/* global document */
import { config, routerTool } from 'utils';
import menus from 'config/menus';
import queryString from 'query-string';
import { queryUser } from 'services/user';
import { getTokenFromLocal } from 'services/authorization';

const { prefix } = config;

export default {
  namespace: 'app',

  state: {
    // 程序菜单
    menus,

    // url pathname
    locationPathname: '',

    // url 请求参数
    locationQuery: {},
  },

  subscriptions: {

    setupHistory ({ dispatch, history }) {
      history.listen((location) => {
        // update global location state
        dispatch({
          type: 'updateState',
          payload: {
            locationPathname: location.pathname,
            locationQuery: queryString.parse(location.search),
          },
        });
      });
    },

    setup ({ dispatch, history }) {

      let tid;
      window.onresize = () => {
        clearTimeout(tid);
        tid = setTimeout(() => {
          // todo 窗口大小修改后，可能需要做一些事情.
          // dispatch({ type: 'changeNavBar' });
        }, 300);
      };

      return history.listen((location) => {
        
        // if (!config.openPages.includes(location.pathname)) {
        dispatch({ type: 'load', payload: { pathname: location.pathname } });
        // }
      });
    },
  },

  reducers: {
    updateState (state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },

  effects: {

    *load ({ payload }, { put }) {
      const { pathname } = payload;
      const { openPages } = config;
      const authWhiteList = [];
      openPages.forEach((_) => {
        if (typeof _ === 'object' && !_.needAuth) {
          authWhiteList.push(_.path);
        }
        if (typeof _ === 'string') {
          authWhiteList.push(_);
        }
      });
      // console.log(authWhiteList);
      if (!authWhiteList.includes(pathname)) {
        yield put({
          type: 'loadInitData',
          payload: {},
        });
      }
    },

    // 加载初始化数据
    *loadInitData ({ payload }, { call, put, select }) {
      let { token, locationPathname, userInfo } = yield select((state) => {
        return {
          token: state.user.token,
          locationPathname: state.app.locationPathname,
          userInfo: state.user.userInfo,
        };
      });

      let localToken = yield call(getTokenFromLocal);
      // console.log(localToken, "localToken");
      if (!token && localToken) {
        yield put({
          type: 'user/updateToken',
          payload: localToken,
        });
        token = localToken;
      }


      if (!token) {
        if (locationPathname === routerTool.getPathByName('Login')) {
          yield put(routerTool.redirectTo('Login'));
        } else {
          yield put(routerTool.redirectTo({
            name: 'Login',
            search: queryString.stringify({
              from: locationPathname,
            }),
          }));
        }
      }

      // 判断是否还存在用户信息, 若不存在则重新获取用户信息。
      if (!userInfo.ID) {
        console.log('load user info ====', userInfo);
        const { success, results: { info } } = yield call(queryUser, payload);
        const {
          School,
          CurrentOrganization,
          Departments,
          Organizations,
          ...UserInfo
        } = (info || {});

        if (success) {
          yield put({
            type: 'user/updateState',
            payload: {
              school: School,
              organization: CurrentOrganization,
              organizations: Organizations,
              userInfo: UserInfo,
            },
          });
        } else {
          console.log('收到了错误?');
          yield put({ type: 'user/clearLoginInfo' });
          yield put({ type: 'toLoginPage' });
          return;
        }
      }
      
      yield put({ type: 'user/checkOrganization' });
    },

    // 到登录页面
    *toLoginPage (_, { put, select }) {
      const { locationPathname } = yield select(_ => _.app);
      yield put(routerTool.redirectTo({
        name: 'Login',
        search: queryString.stringify({
          from: locationPathname,
        }),
      }));
    },

    *toOrganizationAlert (_, { put }) {
      yield put(routerTool.redirectTo({
        name: 'OrganizationAlert',
      }));
    },

  },

};
